package com.hamilton.erik.pt.mobile.android.net.ssl;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.hamilton.erik.pt.mobile.android.R;

import android.content.Context;

public class PtCertSSLSocketFactory {

	public static SSLSocketFactory getSSLSocketFactory(final Context context) 
			throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
			IOException, KeyManagementException {
		
		// Import the KeyStore from the resources
		KeyStore keyStore = KeyStore.getInstance("BKS");
		InputStream inputStream = context.getResources().openRawResource(R.raw.ptkeystore);
		keyStore.load(inputStream, context.getString(R.string.store_pass).toCharArray());
		inputStream.close();
		
		// Set up a TrustManager to trust our KeyStore
		TrustManagerFactory trustManagerFactory = 
				TrustManagerFactory.getInstance(
						TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init(keyStore);

		// Initialize an SSLContext that uses our TrustManager
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

		return sslContext.getSocketFactory();
	}
}
